package com.hb.trade.server.expert.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.expert.dto.ExpertDTO;
import com.hb.core.pojo.expert.dto.ExpertExtractParam;
import com.hb.core.pojo.expert.dto.MajorAmount;
import com.hb.core.pojo.expert.entity.ExpertBase;
import com.hb.core.pojo.expert.entity.ExpertGroupMembers;
import com.hb.core.pojo.expert.mapper.ExpertBaseMapper;
import com.hb.core.pojo.expert.mapper.ExpertGroupMembersMapper;
import com.hb.core.pojo.parent.PageResult;
import com.hb.trade.server.expert.service.ExpertMajorService;
import com.hb.trade.server.expert.service.ExpertService;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.MsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jinhaolin
 * @date 2022/1/18 14:14
 **/
@Service
public class ExpertServiceImpl extends ServiceImpl<ExpertBaseMapper, ExpertBase> implements ExpertService {

    @Autowired
    private ExpertMajorService expertMajorService;
    @Resource
    private ExpertGroupMembersMapper expertGroupMembersMapper;

    /**
     * 抽取几组专业的专家，就查询几次数据库。
     * 因为专家有可能具有几个专业的评标资格，为了防止几组专业都抽中同一个专家，没法在一个sql中拿到所有专业分组的专家。
     * 第一次查询得到的专家，需要作为第二次查询中的回避专家，防止重复抽取到同一个专家。
     * @param expertExtractParam
     * @return
     */
    @Override
    public Message<List<ExpertDTO>> expertExtract(ExpertExtractParam expertExtractParam) {

        // 最终抽取专家的结果
        List<ExpertDTO> expertListResult = new ArrayList<>();

        // 回避专家列表
        List<String> avoidExpertsIdCards = new ArrayList<>();

        // 如果存在抽取记录则说明时补抽的  需要排除当前已抽取的专家
        if (null != expertExtractParam.getGroupId()) {
            // 获取历史抽取的专家
            QueryWrapper<ExpertGroupMembers> expertGroupMembersQueryWrapper = new QueryWrapper<>();
            expertGroupMembersQueryWrapper.lambda().eq(ExpertGroupMembers::getGroupId, expertExtractParam.getGroupId());
            List<ExpertGroupMembers> yiChou = expertGroupMembersMapper.selectList(expertGroupMembersQueryWrapper);
            // 查询已抽取的专家(排除已抽取的专家)
            List<String> avoidExpertList = new ArrayList<>();
            if (!yiChou.isEmpty()) {
                avoidExpertList = yiChou.stream().map(e -> e.getPhoneNum()).collect(Collectors.toList());
                avoidExpertsIdCards.addAll(avoidExpertList);
            }
        }

        if (expertExtractParam.getMajorAmountList() == null || expertExtractParam.getMajorAmountList().size() == 0) {
            return MsgUtil.msg(MsgEnum.SUCCESS.code(), "抽取条件为空", expertListResult);
        }

        if (expertExtractParam.getAvoidExperts() != null) {
            avoidExpertsIdCards.addAll(expertExtractParam.getAvoidExperts());
        }

        // 专家数量不足的提醒消息
        String message = "";

        for (MajorAmount majorAmount : expertExtractParam.getMajorAmountList()) {
            if (majorAmount.getCount() == null || majorAmount.getCount() == 0) {
                return MsgUtil.fail("缺少抽取专家的数量");
            }

            // 每个专家单独抽取
            List<ExpertDTO> result = new ArrayList<>();

            for (int i = 0; i < majorAmount.getCount(); i++) {
                List<ExpertDTO> allExtract = baseMapper.expertAllExtract(majorAmount.getMajorCode(), expertExtractParam.getAvoidEnterprises(), avoidExpertsIdCards, expertExtractParam.getOrgId());

                if (allExtract.isEmpty()) {
                    String majorName = expertMajorService.findByMajorCode(majorAmount.getMajorCode()).getMajorName();
                    return MsgUtil.fail(majorName + "专业专家数量不足");
                }

                // 在抽取到的专家中随机获取专家
                int index = (int) (Math.random() * allExtract.size());
                // 当前抽取到的专家
                ExpertDTO expert = allExtract.get(allExtract.size() == 1 ? 0 : index);
                result.add(expert);

                // 标记当前专家不可继续抽取
                avoidExpertsIdCards.add(expert.getPhoneNumber());

            }

            for (ExpertDTO expertDTO : result) {
                if (expertDTO.getSex() != null && expertDTO.getSex().equals(1)) {
                    expertDTO.setSexStr("女");
                } else if (expertDTO.getSex() != null && expertDTO.getSex().equals(0)) {
                    expertDTO.setSexStr("男");
                }
            }

            expertListResult.addAll(result);

        }

        return MsgUtil.msg(MsgEnum.SUCCESS.code(), message, expertListResult);
    }

    @Override
    public PageResult<ExpertDTO> expertSearch(ExpertDTO expertDTO) {
        Page<ExpertDTO> pages = baseMapper.expertSearch(expertDTO.pages(), expertDTO);
        return PageResult.get(pages);
    }

    /**
     * 查询全部专家信息
     * @param expertDTO
     * @return
     */
    @Override
    public List<ExpertDTO> expertList(ExpertDTO expertDTO) {
        List<ExpertDTO> expertDTOList = baseMapper.expertList(expertDTO);
        return expertDTOList;
    }

    /**
     * 查询专家手机号是否重复
     * @author tian
     * @date 2022-4-26 15:09
     * @param expertDTO
     * @return boolean
     */
    @Override
    public boolean countByPhoneNumberAndOrgId(ExpertDTO expertDTO) {
        Integer integer = baseMapper.countByPhoneNumberAndOrgId(expertDTO);
        return integer > 0 ? false : true;
    }
}
